<template>
  <div class="notice-detail">
    <Row class="margin-top-10">
      <div class="notice-main">
        <Form ref="noticeForm" :model="data" :rules="rule" :label-width="100">
          <FormItem prop="users" label="发送给谁" :error="error.users">
            <Select
              v-model="data.users"
              :disabled="data.type !== 'select'"
              suffix="ios-search"
              filterable
              remote
              :remote-method="remoteMethod"
              style="width: 240px"
              placeholder="搜索用户昵称或者ID"
              multiple
              :max-tag-count="2"
              :max-tag-placeholder="maxTagPlaceholder"
            >
              <Option
                v-for="item in users"
                :key="item._id"
                :value="item._id"
                :label="item.username"
              >
                {{ item.username }}
                <span>&nbsp;&nbsp;({{ item._id }})</span>
              </Option>
            </Select>
            <template v-if="data.type === 'select'">
              <br />已选中用户:&nbsp;&nbsp;
              <Tag v-for="item in data.users" :key="item">{{ item }}</Tag>
            </template>
            <br />
            <RadioGroup v-model="data.type" @on-change="changeType">
              <Radio label="select">
                <span>通过搜索选择用户</span>
              </Radio>
              <Radio label="all">
                <span>全部用户</span>
              </Radio>
              <Radio label="ios" disabled>
                <span>全部苹果用户</span>
              </Radio>
              <Radio label="android" disabled>
                <span>全部安卓用户</span>
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem prop="title" label="消息标题" :error="error.title">
            <Input v-model="data.title" placeholder="请输入消息标题" />
          </FormItem>
          <FormItem
            prop="description"
            label="消息说明"
            :error="error.description"
          >
            <Input v-model="data.description" placeholder="请输入消息说明" />
          </FormItem>
          <FormItem prop="img_url" label="配图" :error="error.previewImg">
            <m-uploader
              :value.sync="data.previewImg"
              :max-size="300 * 1024"
              desc="请上传347x200尺寸大小的图片，否则图片会自动放大来适配当前大小"
            />
          </FormItem>
          <FormItem prop="content" label="消息内容" :error="error.content">
            <RichEditor :onChange="saveContent" :content="data.content" />
          </FormItem>
          <FormItem>
            <Button type="primary" @click="sendNotice" :loading="loading">
              {{ isUpdateOrAdd === 'add' ? '发送' : '更新' }}通知
            </Button>
            <Button type="warning" style="margin-left: 12px" @click="resetForm">
              重置表单
            </Button>
          </FormItem>
        </Form>
      </div>
      <div class="notice-left">
        <div class="notice-phone">
          <div class="notice-preview">
            <header>
              <Icon type="ios-arrow-back" />
              <p class="notice-preview-title">
                {{ data.title || '通知详情' }}
              </p>
            </header>
            <article v-html="data.content" ref="article"></article>
          </div>
        </div>
      </div>
    </Row>
  </div>
</template>

<script>
import { oldHttp } from '@/utils/http';
import RichEditor from '@/components/rich-editor';
import Uploader from '@/components/uploader';

const defaultPreviewImg = 'https://file.lantingshucheng.com/2021-03-06-22-35-48.png';

export default {
  name: 'notice_detail',

  components: {
    RichEditor,
    [Uploader.name]: Uploader,
  },

  data() {
    return {
      loading: false,
      users: {},
      data: {
        type: 'all',
        users: [],
        title: '',
        description: '',
        previewImg: '',
        content: '',
      },
      rule: {
        users: [],
        title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入通知描述', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' },
        ],
      },
      error: {},
      currentId: '',
      isUpdateOrAdd: 'add',
    };
  },
  methods: {
    // 获取通知详情
    getNoticeDetail(id) {
      const noticeId = id || this.$route.params.id;
      this.currentId = noticeId;
      this.isUpdateOrAdd = !noticeId || noticeId === '0' ? 'add' : 'update';
      if (this.isUpdateOrAdd === 'add') {
        // 初始化数据
        this.data = {
          type: 'all',
          users: [],
          title: '',
          description: '',
          previewImg: '',
          content: '',
        };
        return;
      }
      this.loading = true;
      oldHttp
        .get(`/api/admin/notice/${noticeId}/detail`, {}, '获取通知详情')
        .then((res) => {
          this.loading = false;
          if (res.ok) {
            const isNoSelectUser = /(all|ios|android)/g;
            const data = res.data;
            this.data = {
              type: isNoSelectUser.test(data.user) ? data.user : 'select',
              users: isNoSelectUser.test(data.user) ? [] : data.user.split(','),
              title: data.title,
              description: data.description,
              previewImg: data.previewImg || defaultPreviewImg,
              content: data.content,
            };
          }
        });
    },
    changeType(value) {
      if (value === 'select') this.data.users = [];
    },
    maxTagPlaceholder(num) {
      return 'more ' + num;
    },
    // 远程搜索用户
    remoteMethod(query) {
      if (query !== '') {
        oldHttp
          .get(
            '/api/admin/user',
            { page: 1, limit: 1000, name: query },
            '搜索用户'
          )
          .then((res) => {
            if (res.ok) {
              this.users = res.list;
            }
          });
      } else {
        this.users = [];
      }
    },
    resetForm() {
      this.$refs['noticeForm'].resetFields();
    },
    saveContent(value) {
      this.data.content = value;
    },
    sendNotice() {
      this.loading = true;
      if (this.data.type !== 'select') this.data.users = [this.data.type];
      this.$refs['noticeForm'].validate((valid) => {
        if (valid) {
          if (!this.data.users || this.data.users.length <= 0) {
            this.$Message.info('请选择发送用户');
            return;
          }
          // 新增通知
          if (this.isUpdateOrAdd === 'add') {
            oldHttp
              .post(
                '/api/admin/notice',
                {
                  users: this.data.users.join(','),
                  title: this.data.title,
                  description: this.data.description,
                  previewImg: this.data.previewImg || defaultPreviewImg,
                  content: this.data.content,
                  preview: this.$refs.article.innerText
                    .replace(/\s+/g, ' ')
                    .trim()
                    .substring(0, 72),
                },
                '新增通知'
              )
              .then((res) => {
                this.loading = false;
                if (res.ok) {
                  this.$Message.success('发送通知成功');
                  this.$refs['noticeForm'].resetFields();
                  this.$router.back();
                }
              })
              .catch((err) => {
                this.$Message.error('发送通知失败');
                this.loading = false;
              });
          } else {
            // 更新通知
            oldHttp
              .put(
                '/api/admin/notice/' + this.currentId,
                {
                  users: this.data.users.join(','),
                  title: this.data.title,
                  description: this.data.description,
                  previewImg: this.data.previewImg || defaultPreviewImg,
                  content: this.data.content,
                  preview: this.$refs.article.innerText
                    .replace(/\s+/g, ' ')
                    .trim()
                    .substring(0, 72),
                },
                '更新通知'
              )
              .then((res) => {
                this.loading = false;
                if (res.ok) {
                  this.$Message.success('更新通知成功');
                  this.$refs['noticeForm'].resetFields();
                  this.$router.back();
                }
              })
              .catch((err) => {
                this.$Message.error('更新通知失败');
                this.loading = false;
              });
          }
        } else {
          this.loading = false;
        }
      });
    },
  },
  beforeRouteEnter(to, from, next) {
    next((that) => {
      that.getNoticeDetail();
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.getNoticeDetail(to.params.id);
    next();
  },
};
</script>

<style lang="less">
.notice-detail {
  overflow: hidden;

  &__title {
    font-size: 16px;
  }
}

.notice-detail .add-icon {
  float: right;
}

.notice-main {
  width: 100%;
  padding-left: 400px;
  box-sizing: border-box;
  float: left;
  min-height: 100%;
  padding-bottom: 10000px;
  margin-bottom: -10000px;
}

.notice-left {
  width: 400px;
  float: left;
  margin-left: -100%;
  min-height: 100%;
  padding-bottom: 10000px;
  margin-bottom: -10000px;
}

.notice-phone {
  width: 360px;
  height: 750px;
  background: url('../../../images/iphone.png');
  background-size: 100% 100%;
  box-sizing: border-box;
  padding-top: 90px;
}

.notice-preview {
  width: 316px;
  height: 563px;
  margin: 0 auto;
  & > header {
    text-align: center;
    color: #000000;
    font-weight: bold;
    position: relative;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    background: #ffffff;
    border-bottom: 1px solid #f0f0f0;
    & > i {
      position: absolute;
      top: 50%;
      left: 10px;
      transform: translateY(-50%);
    }
  }
  & > article {
    height: 523px;
    padding: 10px;
    background: #ffffff;
    /*隐藏滚动条，当IE下溢出，仍然可以滚动*/
    -ms-overflow-style: none;
    /*火狐下隐藏滚动条*/
    overflow-y: auto;
    overflow-y: -moz-scrollbars-none;
    overflow-x: hidden;
    &::-webkit-scrollbar {
      width: 0px;
    }
    img {
      width: calc(~'100% + 20px');
      height: auto;
      margin-left: -10px;
      max-width: inherit !important;
    }
    ul,
    ol {
      padding-left: 24px;
    }
    h1,
    h2,
    h3 {
      padding-left: 4px;
      border-left: 2px solid #d15f11;
      line-height: 1em;
      margin-top: 10px;
      margin-bottom: 10px;
    }
  }
}
</style>
